package com.study.controller;

import com.study.pojo.Result;
import com.study.utils.SecurityContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * 认证信息接口
 * 访问限制：登录用户可访问
 */
@Slf4j
@RestController
@RequestMapping("/authenticated")
public class AuthenticatedController {
    /**
     * 获取当前登录用户名称
     *
     * @return
     */
    @GetMapping("/getCurrentLoginUserName")
    public Result<String> getCurrentLoginUserName() {
        String userName = SecurityContextUtil.getUserName();
        return new Result<>(userName);
    }

    /**
     * 获取当前登录用户的权限信息
     *
     * @return
     */
    @GetMapping("/getCurrentLoginUserAuth")
    public Result<Collection<GrantedAuthority>> getCurrentLoginUserAuth() {
        Collection<GrantedAuthority> userAuth = SecurityContextUtil.getUserAuth();
        return new Result<>(userAuth);
    }

    /**
     * 获取当前登录用户的权限信息
     *
     * @return
     */
    @GetMapping("/test")
    public void test(HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"name/password\"");
        try {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
